<?php
/**
 * @version     1.0.0
 * @package     com_travel
 * @copyright   Copyright (C) 2013. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      thinh <dinhducthinh88@yahoo.com> - http://
 */

// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');
/**
 * Tour model.
 */
class TravelModelField extends JModelAdmin
{

	public function getTable($name='Field',$prefix='TravelTable',$config = array()){
		return parent::getTable($name,$prefix,$config);
	}
	
	public function getForm($data = array(), $loadData = true)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();
		
		// Get the form.
		$form = $this->loadForm('com_travel.field', 'field', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form)) {
			return false;
		}
		
		return $form;
	}
	
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_travel.edit.field.data', array());
		
		if (empty($data))
		{
			$data = $this->getItem();
			$data->catsid = explode(',', $data->catsid);
		}
		
		return $data; 
	}
	
	//Add field to table #__travel_tours
	public function addTourField($field)
	{
		global $app;
		$db 	= $this->getDbo();		
		//check column exist
		$db->setQuery("SELECT count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$app->getCfg('db')."' AND TABLE_NAME = '".$db->getPrefix()."travel_tours' AND column_name='{$field['field_name']}'");
		$exist = $db->loadResult();
		
		if (!$exist) {
			switch($field['field_type']){
				case "checkbox":
					$type = "TINYINT(1) DEFAULT '0'";
					break;
					
				case "select":
				case "radio":
					$type = "VARCHAR(255) NOT NULL";
					break;
					
				default:
					$type = 'TEXT NOT NULL';
					break;
			}
			$db->setQuery("ALTER TABLE #__travel_tours ADD `".$field['field_name']."` $type ");
			$result = $db->query();
		}
	}
	
	//Delte field from table #__travel_tours and Field values
	public function deleteField($ids)
	{
		global $app;
		$db 	= $this->getDbo();
		
		//Load list field to delete
		$db->setQuery("SELECT id,field_name FROM #__travel_fields WHERE id IN ($ids) ");
		$fields = $db->loadObjectList();
		
		foreach ($fields as $field) {
				
			//check column exist
			$db->setQuery("SELECT count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$app->getCfg('db')."' AND TABLE_NAME = '".$db->getPrefix()."travel_tours' AND column_name='{$field->field_name}'");
			$exist = $db->loadResult();

			//Delete tours field
			if ($exist) {
				$db->setQuery("ALTER TABLE #__travel_tours DROP `".$field->field_name."`");
				$db->query();
			}
			
			$this->deleteFieldValues($field->id);
		}
	}
	
	public function deleteFieldValues($fieldid) {
		$db = $this->getDbo();
		$db->setQuery("DELETE FROM #__travel_field_values WHERE fieldid = ".(int)$fieldid);
		$db->query();
	}
	
	/* public function getFieldValues($id){
		$db = $this->getDbo();
		if($id){
			$db->setQuery("SELECT * FROM #__travel_field_values WHERE fieldid = ".(int)$id);
			return $values = $db->loadObjectList();
		}
	} */
	
	public function saveFieldValues($field_type, $fieldNames, $fieldValues, $fieldid)
	{	
		switch($field_type) {
			case "select":
			case "multiselect":
			case "radio":
			case "multicheckbox":
			case "price":
				$this->deleteFieldValues($fieldid);
				$j=0;$i=0;
				while(isset($fieldNames[$i])){
					$fieldName  = $fieldNames[$i];
					$fieldValue = $fieldValues[$i];
					$i++;
						
					if(trim($fieldName)!=null || trim($fieldName)!='') {
						$this->_db->setQuery( "INSERT INTO #__travel_field_values (fieldid,field_title,field_value,ordering)"
								. " VALUES('".(int)$fieldid."',".$this->_db->Quote($fieldName).",".$this->_db->Quote($fieldValue).",".(int)$j.")"
						);
						$this->_db->query();
						$j++;
					}
				}
				break;
			case 'radioimage':
			case 'multicheckboximage':
				$this->deleteFieldValues($fieldid);
				$j=0;$i=0;
				while(isset($fieldImagesSelect[$i])){
					$fieldName  = $fieldImagesSelect[$i];
					$fieldValue = $fieldImagesValues[$i];
					$i++;
						
					if(trim($fieldName)!=null && trim($fieldName)!='' && trim($fieldName)!='null') {
						$this->_db->setQuery( "INSERT INTO #__travel_field_values (fieldid,field_title,field_value,ordering)"
								. " VALUES('".(int)$fieldid."',".$this->_db->Quote($fieldName).",".$this->_db->Quote($fieldValue).",".(int)$j.")"
						);
						$this->_db->query();
						$j++;
					}
				}
				break;
		}
	}
	
	/**
	 * Method to stick records.
	 *
	 * @param   array    &$pks   The ids of the items to publish.
	 * @param   integer  $value  The value of the published state
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	function required(&$pks, $value = 1)
	{
		// Initialise variables.
		$user = JFactory::getUser();
		$table = $this->getTable();
		$pks = (array) $pks;

		// Access checks.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk))
			{
				if (!$this->canEditState($table))
				{
					// Prune items that you can't change.
					unset($pks[$i]);
					JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
				}
			}
		}

		// Attempt to change the state of the records.
		if (!$table->required($pks, $value, $user->get('id')))
		{
			$this->setError($table->getError());
			return false;
		}

		return true;
	}
	
	/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param   JTable  $table  A record object.
	 *
	 * @return  array  An array of conditions to add to add to ordering queries.
	 *
	 * @since   1.6
	 */
	protected function getReorderConditions($table)
	{
		$condition = array();
		$condition[] = 'position_display = '. (int) $table->position_display;
		return $condition;
	}
}